package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper mapper;

    @Override
    @Transactional(readOnly = true)
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Role> list = this.mapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void saveOrUpdate(Role entity, Long[] ids) {
        if(entity.getId()==null){
            this.mapper.insert(entity);
        }else {
            this.mapper.updateByPrimaryKey(entity);
            this.mapper.deleteRelation(entity.getId());
        }
        if((ids !=null)&&(ids.length>0)){
            for (Long perm:ids) {
                this.mapper.insertRelation(entity.getId(),perm);
            }
        }
    }

    @Override
    public void delete(Long id) {
        this.mapper.deleteByPrimaryKey(id);
        this.mapper.deleteRelation(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Role get(Long id) {
        return this.mapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Role> list() {
        return this.mapper.selectAll();
    }
}
